package com.aispeech.asr.webase.config;

import io.netty.channel.ChannelOption;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.reactive.ClientHttpConnector;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.http.client.reactive.ReactorResourceFactory;
import org.springframework.web.reactive.function.client.ExchangeStrategies;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;

import java.util.function.Function;

@Configuration
public class WebClientConfig {
    @Bean
    public ReactorResourceFactory resourceFactory() {
        ReactorResourceFactory factory = new ReactorResourceFactory();
        factory.setUseGlobalResources(false);
        return factory;
    }

    @Bean
    public WebClient webClient(ReactorResourceFactory resourceFactory) {

        Function<HttpClient, HttpClient> mapper = client -> {
            client.tcpConfiguration(tcp -> {
                tcp.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);

//                tcp.doOnConnected(conn -> conn
//                        .addHandlerLast(new ReadTimeoutHandler(10))
//                        .addHandlerLast(new WriteTimeoutHandler(10)));

                return tcp;
            });

            return client;
        };

        ClientHttpConnector connector =
                new ReactorClientHttpConnector(resourceFactory, mapper);


        ExchangeStrategies strategies = ExchangeStrategies.builder()
                .codecs(configurer -> configurer
                        .defaultCodecs()
                        .maxInMemorySize(800 * 1024 * 1024))
                .build();

        return WebClient.builder().clientConnector(connector).exchangeStrategies(strategies).build();
    }
}
